//
//  MyGuestController.m
//  QQplayground
//
//  Created by zhangxy on 2018/8/22.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "MyGuestController.h"

#import "ZZUserListCell.h"
#define cellIdentifier @"ZZUserListCell"

#import "UserInfoController.h"

@interface MyGuestController ()<ZZUserListCellDelegate>{
    int _page;
}

@property(nonatomic,strong) NSMutableArray *sectionArr;

@property(nonatomic,strong) UITableView *listTable;
@property(nonatomic,strong) ZTextField *textField;

@end

@implementation MyGuestController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"访客";
    
    [self setNavigationBar];
    
    self.navigationController.navigationBarHidden = NO;
    
    [self.view setBackgroundColor:UIColorFromRGB(BgSystemColor)];
    [self createTableView];
    
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self loadBegin];
    
    
    MJRefreshBackStateFooter *footer = [MJRefreshBackStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    _listTable.footer = footer;
    
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadBegin];
    }];
    _listTable.header = header;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
}


-(void)createTableView{
    _sectionArr = [[NSMutableArray alloc] init];
    
    _listTable=[self.view createTableView:self cell:cellIdentifier];
    [_listTable setFrame:self.view.bounds];
    _listTable.layer.cornerRadius = 10.0f;
    _listTable.layer.masksToBounds = YES;
    [_listTable setBackgroundColor:UIColorFromRGB(TextWhiteColor)];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    UIView *footer =[ [UIView alloc]init];
    footer.backgroundColor = [UIColor clearColor];
    [_listTable setTableFooterView:footer];
    
    [_listTable setSeparatorColor:LINE_COLOR];
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    
    
    [self setTableSeparatorInset];
}

-(void)onItemClick:(User *)user type:(ZZUserItemClickType)type{
    if(type == ZZUserItemClickAttent){
        NSString *url = API_Addfollow;
        if([user.user_relation intValue] == 1){
            url = API_Delfollow;
        }
        [NetworkUtil POST:url parameters:@{@"user_id":user.user_id,
                                           @"session_uid":[UserUtil getUser].user_id}
                  success:^(id responseObject, NSDictionary *dict) {
                      if([user.user_relation intValue] == 1){
                          user.user_relation = @"0";
                      }else{
                          user.user_relation = @"1";
                      }
                      [self.listTable reloadData];
                  } failure:^(NSError *error, NSString *message) {
                      [PopUtil showMessage:convertToString(message)];
                  }];
    }
    
}


-(void)loadBegin{
    _page = 1;
    [self loadMoreData];
}


/**
 加载更多
 */
-(void)loadMoreData{
    NSString *api = API_MyVisitlist;
    
    [NetworkUtil POST:api parameters:@{@"session_uid":_user_id,@"page":convertIntToString(_page),@"page_size":@"30"} success:^(id responseObject, NSDictionary *dictionary) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
        if(self->_page == 1){
            [self.sectionArr removeAllObjects];
        }
        NSArray *arr = dictionary[@"data"][@"list"];
        for(NSDictionary *item in arr){
            NSString *addtime = [item[@"add_time"] substringToIndex:6];
            NSMutableDictionary *lastObj = [_sectionArr lastObject];
            NSMutableArray *tempArr = nil;
            if(lastObj!=nil && [lastObj[@"time"] isEqual:addtime]){
                tempArr = lastObj[@"arr"];
            }else{
                tempArr = [[NSMutableArray alloc] init];
                NSMutableDictionary *obj = [[NSMutableDictionary alloc] init];
                [obj setObject:tempArr forKey:@"arr"];
                [obj setObject:addtime forKey:@"time"];
                [_sectionArr addObject:obj];
            }
            [tempArr addObject:item];
        }
        [self.listTable reloadData];
        if(convertToString(dictionary[@"data"][@"page"]).length>0){
            if([dictionary[@"data"][@"page"] intValue] < [dictionary[@"data"][@"pages"] intValue]){
                self->_page = [dictionary[@"data"][@"page"] intValue] + 1;
            }
        }
        
    } failure:^(NSError *error, NSString *message) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
    }];
}



#pragma mark UITableView delegate Start
// 返回section数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _sectionArr.count;
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return  44;
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
    [headerView setBackgroundColor:UIColorFromRGB(BgSystemColor)];
//    if(section == 0){
        UILabel *lab = [self createLabel];
        NSMutableDictionary *item = _sectionArr[section];
        [lab setTextColor:UIColorFromRGB(TextSizeOneColor)];
        [lab setFrame:CGRectMake(10, 0, ScreenWidth - 20, 44)];
        
        [lab setText:item[@"time"]];
        
        [headerView addSubview:lab];
//    }
    return headerView;
}

// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSMutableDictionary *item = _sectionArr[section];
    NSArray *arr = item[@"arr"];
    return arr.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZZUserListCell *cell = (ZZUserListCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[ZZUserListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.btnLevel.hidden = YES;
    cell.btnVip.hidden = YES;
    cell.btnAttent.hidden = YES;
    NSMutableDictionary *item = _sectionArr[indexPath.section];
    NSArray *arr = item[@"arr"];
    NSDictionary *entity = [arr objectAtIndex:indexPath.row];
    User *u = [[User alloc] initWithDictionary:entity];
    
    [cell.labDesc setTextAlignment:NSTextAlignmentRight];
    NSString *addTime = entity[@"add_time"];
    if(convertToString(addTime).length > 6){
        addTime = [convertToString(addTime) substringFromIndex:6];
        [cell.labDesc setText:addTime];
    }else{
        [cell.labDesc setText:@""];
    }
    cell.labName.attributedText = [NSAttributedString new];
    [cell dataToView:u];
    cell.delegate = self;
    return cell;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    NSMutableDictionary *item = _sectionArr[indexPath.section];
    NSArray *arr = item[@"arr"];
    NSDictionary *entity = [arr objectAtIndex:indexPath.row];
    
    UserInfoController *vc = [[UserInfoController alloc] init];
    vc.user_id = entity[@"user_id"];
    [self openPushVC:vc];
}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row < _sectionArr.count){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }else{
        UIEdgeInsets inset = UIEdgeInsetsMake(0, ScreenWidth, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}

-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}
#pragma mark UITableView delegate end

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
